package Sort.面试;

import java.util.Arrays;

/**
 * ============  二分查找    ==============
 *
 * 实现数组中查找元素的方法，要求方法输入一个有序数组和一个整形n,
 *   n 为数组中出现的位置
 */

public class BinarySearch {

    public static int[] INT_ARRAY = {1,2,4,5,7,9,11};

    public static int BinarySearchSort(int[] array, int n){
        if(array.length == 0 ){
            return -1;
        }
        //正序排序
        Arrays.sort(array);

        int right = array.length;
        int left = 0;
        int middle = (left + right)/2;

        while(left < right){
            if(n < array[middle]){
                right = middle;
            }else if(n > array[middle]){
                left = middle;
            }else{
                return middle;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(BinarySearchSort(INT_ARRAY,5));
    }
}
